package com.cqnu.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.cqnu.common.Constant;
import com.cqnu.entity.Paper;
import com.cqnu.entity.PaperLog;
import com.cqnu.entity.Teacher;
import com.cqnu.entity.ThesisStudent;
import com.cqnu.entity.commonModel.AjaxResult;
import com.cqnu.entity.commonModel.PageParameters;
import com.cqnu.util.DateUtils;
import com.cqnu.util.ListUtil;
import com.cqnu.util.StringUtil;

@Controller
@RequestMapping("/teacher")
public class TeacherController extends BaseController {

	/**
	 * 论文审核
	 */
	@RequestMapping("/goPaperCheck.do")
	public String goQueryThesis(HttpServletRequest request, ModelMap modelMap) {

		Teacher sessionInfo = (Teacher) this.getSession(request,
				Constant.SESSION_USER_KEY);
		String sessionRole = (String) this.getSession(request,
				Constant.SESSION_ROLE_KEY);

		// 用户未登录--返回登录页
		if (sessionInfo == null) {
			// Message报出
			modelMap.addAttribute("errorMessage", "您还未登录或身份已过期，请登录后进行操作！");
			return "error";
		}
		// 用户角色错误--返回登录页
		if (!Constant.LOGIN_TYPE_TEA.equals(sessionRole)) {
			// Message报出
			modelMap.addAttribute("errorMessage", "您没有该资源操作权限！");
			return "error";
		}

		Map<String, Object> map = new HashMap<String, Object>();

		// 拉取专业
		map.put("majorId", sessionInfo.getMajorId());
		modelMap.addAttribute("major", JSON.toJSON(majorService.find(map)
				.get(0)));

		return "/teacher/paperCheck";
	}

	/**
	 * 论文审核 - 数据列表
	 */
	@RequestMapping("/paperCheckData.do")
	@ResponseBody
	public AjaxResult paperCheckData(HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap,
			PageParameters par, Paper filterPaper) throws Exception {

		Teacher sessionInfo = (Teacher) this.getSession(request,
				Constant.SESSION_USER_KEY);
		String sessionRole = (String) this.getSession(request,
				Constant.SESSION_ROLE_KEY);

		// 用户未登录--返回登录页
		if (sessionInfo == null) {
			response.sendRedirect(request.getContextPath()
					+ "/home/errorInfo.do");
			return null;
		}
		// 用户角色错误--返回登录页
		if (!Constant.LOGIN_TYPE_TEA.equals(sessionRole)) {
			response.sendRedirect(request.getContextPath()
					+ "/home/errorRole.do");
			return null;
		}

		// 教师查询条件
		List<Integer> list = new ArrayList<Integer>();
		list.add(Constant.PAPER_STUDENT_PASS);
		list.add(Constant.PAPER_STUDENT_SUBMIT);

		AjaxResult aj = new AjaxResult();
		Map<String, Object> map = this.getMap(par);

		// 查询当前教师下，所有学生的申报信息
		map.put("teacherId", sessionInfo.getId());
		map.put("status", Constant.THESIS_STUDENT_PASS);
		map.put("statusList", list);

		if (null != filterPaper) {
			if (StringUtil.notEmpty(filterPaper.getTitle())) {
				map.put("title", "%" + filterPaper.getTitle() + "%");
			}
			if (filterPaper.getAchievement() != null) {
				map.put("achievement", filterPaper.getAchievement());
			}
		}
		List<Paper> paperList = paperService.getPaperByTeaId(map);

		aj.setRows(paperList);
		aj.setTotal(paperList.size());
		return aj;
	}

	/**
	 * 论文审核 - 审核按钮操作
	 */
	@RequestMapping("/checkPaper.do")
	@ResponseBody
	public AjaxResult checkPaper(HttpServletRequest request, ModelMap modelMap,
			Paper obj) {
		AjaxResult aj = new AjaxResult();
		if (paperService.update(obj) == 1) {
			aj.setMessage("审核成功");
			aj.setSuccess(true);
			paperLogService
			.add(new PaperLog(DateUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"), obj.getStuId(),
					((Teacher) this.getSession(request,
							Constant.SESSION_USER_KEY)).getId(), obj
							.getState(),obj.getRemark()));
			return aj;
		}
		aj.setMessage("审核失败");
		aj.setSuccess(false);
		return aj;
	}

	/**
	 * 审核日志
	 */
	@RequestMapping("/goPaperReview.do")
	public String goPaperReview(HttpServletRequest request, ModelMap modelMap) {

		Teacher sessionInfo = (Teacher) this.getSession(request,
				Constant.SESSION_USER_KEY);
		String sessionRole = (String) this.getSession(request,
				Constant.SESSION_ROLE_KEY);

		// 用户未登录--返回登录页
		if (sessionInfo == null) {
			// Message报出
			modelMap.addAttribute("errorMessage", "您还未登录或身份已过期，请登录后进行操作！");
			return "error";
		}
		// 用户角色错误--返回登录页
		if (!Constant.LOGIN_TYPE_TEA.equals(sessionRole)) {
			// Message报出
			modelMap.addAttribute("errorMessage", "您没有该资源操作权限！");
			return "error";
		}

		return "/teacher/paperLog";
	}

	/**
	 * 审核日志 - 数据列表
	 */
	@RequestMapping("/paperLogData.do")
	@ResponseBody
	public AjaxResult paperLogData(HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap, PaperLog obj,
			PageParameters par) throws Exception {

		Teacher sessionInfo = (Teacher) this.getSession(request,
				Constant.SESSION_USER_KEY);
		String sessionRole = (String) this.getSession(request,
				Constant.SESSION_ROLE_KEY);

		// 用户未登录--返回登录页
		if (sessionInfo == null) {
			response.sendRedirect(request.getContextPath()
					+ "/home/errorInfo.do");
			return null;
		}
		// 用户角色错误--返回登录页
		if (!Constant.LOGIN_TYPE_TEA.equals(sessionRole)) {
			response.sendRedirect(request.getContextPath()
					+ "/home/errorRole.do");
			return null;
		}

		AjaxResult aj = new AjaxResult();
		Map<String, Object> map = this.getMap(par);
		map.put("teacherId", sessionInfo.getId());
		if (null != obj) {
			if (null != obj.getState()) {
				map.put("state", obj.getState());
			}
		}
		List<PaperLog> paperList = paperLogService.getPaperLogByTeaId(map);

		aj.setRows(paperList);
		aj.setTotal(paperLogService.getTotal(this.clearPar(map)).intValue());
		return aj;
	}

	/**
	 * 课题审核
	 */
	@RequestMapping("/goThesisCheck.do")
	public String goThesisCheck(HttpServletRequest request, ModelMap modelMap) {

		Teacher sessionInfo = (Teacher) this.getSession(request,
				Constant.SESSION_USER_KEY);
		String sessionRole = (String) this.getSession(request,
				Constant.SESSION_ROLE_KEY);

		// 用户未登录--返回登录页
		if (sessionInfo == null) {
			// Message报出
			modelMap.addAttribute("errorMessage", "您还未登录或身份已过期，请登录后进行操作！");
			return "error";
		}
		// 用户角色错误--返回登录页
		if (!Constant.LOGIN_TYPE_TEA.equals(sessionRole)) {
			// Message报出
			modelMap.addAttribute("errorMessage", "您没有该资源操作权限！");
			return "error";
		}

		Map<String, Object> map = new HashMap<String, Object>();

		// 拉取专业
		map.put("majorId", sessionInfo.getMajorId());
		modelMap.addAttribute("major", JSON.toJSON(majorService.find(map)
				.get(0)));

		return "teacher/thesisCheck";
	}

	/**
	 * 课题审核 - 数据列表
	 */
	@RequestMapping("/thesisCheckData.do")
	@ResponseBody
	public AjaxResult thesisCheckData(HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap, PageParameters par)
			throws Exception {

		Teacher sessionInfo = (Teacher) this.getSession(request,
				Constant.SESSION_USER_KEY);
		String sessionRole = (String) this.getSession(request,
				Constant.SESSION_ROLE_KEY);

		// 用户未登录--返回登录页
		if (sessionInfo == null) {
			response.sendRedirect(request.getContextPath()
					+ "/home/errorInfo.do");
			return null;
		}
		// 用户角色错误--返回登录页
		if (!Constant.LOGIN_TYPE_TEA.equals(sessionRole)) {
			response.sendRedirect(request.getContextPath()
					+ "/home/errorRole.do");
			return null;
		}

		// 教师查询条件
		List<Integer> list = new ArrayList<Integer>();
		list.add(Constant.THESIS_STUDENT_PASS);
		list.add(Constant.THESIS_STUDENT_SUBMIT);

		AjaxResult aj = new AjaxResult();
		Map<String, Object> map = this.getMap(par);
		// 查询当前教师下，所有学生的申报信息
		map.put("teacherId", sessionInfo.getId());
		map.put("statusList", list);

		aj.setRows(thesisStudentService.queryThesisApply(map));
		aj.setTotal(thesisStudentService.getTotal(this.clearPar(map)).intValue());
		return aj;
	}

	/**
	 * 课题审核 - 审核操作
	 */
	@RequestMapping("/addOrUpdateThesisCheck.do")
	@ResponseBody
	public AjaxResult addOrUpdateThesisCheck(HttpServletRequest request,
			HttpServletResponse response, ThesisStudent thesisStu)
			throws Exception {

		Teacher sessionInfo = (Teacher) this.getSession(request,
				Constant.SESSION_USER_KEY);
		String sessionRole = (String) this.getSession(request,
				Constant.SESSION_ROLE_KEY);

		// 用户未登录--返回登录页
		if (sessionInfo == null) {
			response.sendRedirect(request.getContextPath()
					+ "/home/errorInfo.do");
			return null;
		}
		// 用户角色错误--返回登录页
		if (!Constant.LOGIN_TYPE_TEA.equals(sessionRole)) {
			response.sendRedirect(request.getContextPath()
					+ "/home/errorRole.do");
			return null;
		}

		AjaxResult aj = new AjaxResult();

		// 数据校验
		if (thesisStu.getId() == null) {
			aj.setSuccess(false);
			aj.setMessage("参数为空！");
			return aj;
		}

		ThesisStudent newTs = new ThesisStudent();
		// 若已通过，可更改备注，不能更改状态
		newTs.setId(thesisStu.getId());
		newTs.setRemark(thesisStu.getRemark());
		// 根据ID拉取课题申报信息，判断状态是否为'审核通过'
		ThesisStudent tsInfo = thesisStudentService.getById(thesisStu.getId());
		if (null != tsInfo) {
			if (Constant.THESIS_STUDENT_PASS == tsInfo.getStatus()) {
				thesisStudentService.update(newTs);
				aj.setSuccess(false);
				aj.setMessage("课题已审核通过，不能更改！");
				return aj;
			}
			// 若未通过，则更新审核状态
			newTs.setStatus(thesisStu.getStatus());

			if (thesisStudentService.update(newTs) == 1) {
				aj.setSuccess(true);
				aj.setMessage("审核成功！");
				if (Constant.THESIS_STUDENT_PASS == newTs.getStatus()) {
					// 课题审核通过后自动添加一条论文数据
					Paper paper = new Paper();
					paper.setStuId(tsInfo.getStuId());
					paper.setCreattime(DateUtils.format(new Date(),
							"yyyy-MM-dd HH:mm:ss"));
					paper.setState(Constant.PAPER_STUDENT_NOPASS);
					paper.setAchievement(0);
					paperService.add(paper);
				}
				return aj;
			}
		}
		aj.setSuccess(false);
		aj.setMessage("操作失败！");
		return aj;
	}

	/**
	 * 课题审核 - 获取课题数据，显示按钮弹出框数据
	 */
	@RequestMapping("/getThesisCheckById.do")
	@ResponseBody
	public AjaxResult getThesisCheckById(HttpServletRequest request,
			HttpServletResponse response, int id) throws Exception {

		Teacher sessionInfo = (Teacher) this.getSession(request,
				Constant.SESSION_USER_KEY);
		String sessionRole = (String) this.getSession(request,
				Constant.SESSION_ROLE_KEY);

		// 用户未登录--返回登录页
		if (sessionInfo == null) {
			response.sendRedirect(request.getContextPath()
					+ "/home/errorInfo.do");
			return null;
		}
		// 用户角色错误--返回登录页
		if (!Constant.LOGIN_TYPE_TEA.equals(sessionRole)) {
			response.sendRedirect(request.getContextPath()
					+ "/home/errorRole.do");
			return null;
		}

		AjaxResult aj = new AjaxResult();
		Map<String, Object> map = new HashMap<String, Object>();
		// 根据id获取申报信息
		map.put("id", id);
		List<ThesisStudent> result = thesisStudentService.queryThesisApply(map);
		if (ListUtil.isNotEmpty(result)) {
			if (Constant.THESIS_STUDENT_PASS == result.get(0).getStatus()) {
				aj.setSuccess(false);
				aj.setMessage("课题已审核通过，不能更改！");
			} else {
				aj.setSuccess(true);
				aj.setData(result.get(0));
			}
			return aj;
		}
		aj.setSuccess(false);
		aj.setMessage("系统繁忙，请重试!");
		return aj;
	}

}
